<template>
  <div>
    <el-container>
      <el-header>积分商品管理</el-header>
      <el-main>
        <el-button @click="showAddwindow=true" type="success">添加积分商品</el-button>
        <el-input v-model="param.name" placeholder="请输入商品名" style="width: 20%"></el-input>
        <el-button type="primary" @click="search()" round>搜索</el-button>

        <el-table :data="page.records" style="width: 100%">
          <el-table-column prop="name" label="商品名" width="180">
          </el-table-column>
          <el-table-column prop="price" label="单价" width="180">
          </el-table-column>
          <el-table-column prop="state" label="商品状态" width="180" :formatter="formatGoodsState">
          </el-table-column>
          <el-table-column prop="number" label="库存量" width="180">
          </el-table-column>
          <el-table-column prop="freeze" label="冻结量" width="180">
          </el-table-column>

          <el-table-column label="操作" width="300">
            <template #default="scope">
              <el-button @click="changeStatus(scope.row)" type="text" size="small">修改状态</el-button>
              <el-button type="text" size="small" @click="readyChange(scope.row)">修改信息</el-button>
              <el-button type="text" size="small" @click="remove(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row>
          <el-col :span="12">
            <el-dialog v-loading="loading" title="新增操作" :visible.sync="showAddwindow">
              <div>
                商品名称：<el-input v-model="newGoods.name" placeholder="请输入商品名称" clearable style="width: 50%;"></el-input><br>
                商品类别:
                <el-select v-model="newGoods.typeId" clearable placeholder="请选择">
                  <el-option v-for="item in goodsTypes" :key="item.id" :label="item.typeName" :value="item.id"></el-option>
                </el-select><br>
                商品价格：<el-input-number v-model="newGoods.price" controls-position="right" :min="1" placeholder="请输入价格"></el-input-number><br>
                库存量：<el-input v-model="newGoods.number" placeholder="请输入库存量" clearable style="width: 50%;"></el-input><br>
                <el-button @click="add()" type="success" round>立 刻 新 增</el-button>
                <el-button @click="showAddwindow = false" type="danger" round>取 消</el-button>
              </div>
            </el-dialog>
          </el-col>
        </el-row>
      </el-main>

      <el-dialog v-loading="loading" title="更改商品信息" :visible.sync="dialogVisible" width="35%">
        <el-switch style="display: block" v-model="changePictor" active-color="#13ce66" inactive-color="#ff4949"
          active-text="修改图片" inactive-text="修改信息">
        </el-switch>
        <div v-show="!changePictor">
          商品名：<el-input v-model="changeGoods.name" placeholder="请输入商品名" clearable style="width: 50%;"></el-input><br>
          商品价格：<el-input v-model="changeGoods.price" placeholder="请输入商品价格" clearable style="width: 50%;"></el-input><br>
          库存：<el-input v-model="changeGoods.number" placeholder="请输入库存" clearable style="width: 50%;"></el-input><br>
          <el-input v-show="false" v-model="changeGoods.oldImg"></el-input>
          <el-input v-show="false" v-model="changeGoods.id"></el-input>
        </div>

        <div v-show="changePictor">更改图片：</div>
        <el-upload v-if="changePictor" :headers="headers" :data="image" name="image" ref="upload" action="http://192.168.70.131:9001/pointsmall/goods/uploadImg"
          :file-list="fileList" :auto-upload="false" :on-success="handleUploadSuccess" @error="handleUploadError" @change="handleUploadChange">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitModify">立即修改</el-button>
        </el-upload>
        <el-button @click="modify2" type="success" round v-if="!changePictor">立即修改</el-button>
        <el-button @click="dialogVisible = false" type="danger" round>取 消</el-button>
      </el-dialog>

      <el-footer>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.pageNum"
          :page-sizes="[3, 4, 5]" :page-size="page.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="page.total">
        </el-pagination>
      </el-footer>
    </el-container>
  </div>
</template>


<script>
  export default {
    name: "pointGoodsAdmin",
    data() {
      return {
        image: null,
        showAddwindow: false,
        newGoods: {},
        page: {},
        pageNum: 0,
        pageSize: 0,
        loading: true,
        headers: {},
        fileList: [],
        goodsTypes: [],
        dialogVisible: false,
        changeGoods: {},
        userId: 0,
        phoneCode: "",
        changePictor: false,
        param: {},
        addDiscount: false,
        discounts: [],
        choosenDiscount: null,
      }
    },
    monted(){
      this.selectListGoodsType()
        this.loadAllPointGoods(this.pageNum, this.pageSize)
        this.headers["token"] = localStorage.getItem("token");
    }
    ,
    methods: {
      add() {
        this.showAddwindow = false
        this.$http.post("/pointsmall/goods/addGoods", this.newGoods).then(resp => {
          if (resp.data.code == 200) {
            this.$message.success(resp.data.message)
          } else {
            this.$message.error(resp.data.message)
          }
          this.loadAllPointGoods(this.pageNum, this.pageSize)
          console.log(resp.data.data)
        })
      },
      handleUploadSuccess(response, file, fileList) {
        console.log('Upload success:', response, file, fileList);
        if (response.code === 200) {
          let img = response.data;
          this.$http.get("/pointsmall/goods/changePictor", {
            params: {
              id: this.changeGoods.id,
              img: img
            }
          }).then(resp => {
            if (resp.data.code == 200) {
              this.$message.success(resp.data.message)
              this.loadAllPointGoods(this.pageNum, this.pageSize);
              this.dialogVisible = false;
            } else {
              this.$message.error(resp.data.message)
            }
          })
        }
      },
      handleUploadError(err, file, fileList) {
        console.error('Upload error:', err, file, fileList);
      },
      handleUploadChange(file, fileList) {
        console.log('Upload change:', file, fileList);
      },
      submitUpload() {
        this.$refs.upload.submit();
      },
      submitModify() {
        this.submitUpload();
      },
      updatePointDiscount() {
        console.log(this.choosenDiscount)
      },
      consoleTime() {
        console.log(this.newGoods.endDate)
      },
      selectListGoodsType() {
        this.$http.get("/pointsmall/goodsType/getAllList").then(resp => {
          this.goodsTypes = resp.data.data
          console.log(resp.data)
        })
      },
      remove(row) {
        console.log(row.id);
        let goodsId = row.id
        this.$http.get("/pointsmall/goods/del?goodsId=" + goodsId).then(resp => {
          this.loadAllPointGoods(this.pageNum, this.pageSize)
        })
      },
      readyChange(row) {
        this.dialogVisible = true
        this.changeGoods = row
        this.changeGoods.oldImg = row.medicineImage
      },
      changeStatus(row) {
        console.log(row)
        const newStatus = row.state == 0 ? 2 : 0
        const id = row.id
        this.$http.post("/pointsmall/goods/changeGoodsState", {
          state: newStatus,
          id: id,
        }).then(resp => {
          this.loadAllPointGoods(this.pageNum, this.pageSize)
        })
      },
      formatGoodsState(row) {
        switch (row.state) {
          case 0:
            return '正常';
          case 1:
            return '删除';
          case 2:
            return '下架';
          default:
            return '未知状态';
        }
      },
      handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.loadAllPointGoods(this.pageNum, this.pageSize)
        console.log(`每页 ${pageSize} 条`);
      },
      handleCurrentChange(pageNum) {
        this.pageNum = pageNum;
        console.log("当前拿到的页数:" + this.pageNum)
        this.loadAllPointGoods(this.pageNum, this.pageSize)
        console.log(`当前页: ${pageNum}`);
      },
      loadAllPointGoods(pageNum, pageSize) {
        this.$http.get("/pointsmall/goods/loadAllPage", {
          params: {
            pageNum: pageNum,
            pageSize: pageSize
          }
        }).then(resp => {
          this.page = resp.data.data
        })
      },
      search() {
        this.pageNum = 1; // 重置 pageNum 为第一页
        this.$http.get("/pointsmall/goods/loadGoodsByName", {
          params: {
            name: this.param.name,
            pageNum: this.pageNum,
            pageSize: this.pageSize
          }
        }).then(resp => {
          console.log(resp.data)
          this.page = resp.data.data
        })
      },
      modify2() {
        this.$http.post("/pointsmall/goods/modifyGoods.api",
          this.changeGoods
        ).then(resp => {
          console.log(resp.data)
          this.dialogVisible = false;
          this.loadAllPointGoods(this.pageNum, this.pageSize)
        })
      }
    },
    // created() {
    // }
  }
</script>

<style>

</style>
